package com.geek.bams.dao;
import com.geek.bams.entity.*;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 *@Date 2025/11/23
 *@Author wangpeng
 *@Description TODO
 */


public class MyBatisDao implements IDao<Account, List<Account>> {

    private SqlSessionFactory sqlSessionFactory;
    private Long id;

    public MyBatisDao() {
        // 初始化MyBatis
        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("SqlMapConfig.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            // 初始化ID
            loadMaxIdFromDatabase();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean insert(Account account) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            // 创建传递给MyBatis的参数Map
            Map<String, Object> paramMap = createParamMap(account);
            int result = session.insert("com.geek.bams.mapper.AccountMapper.insert", paramMap);

            // 更新ID序列
            session.update("com.geek.bams.mapper.AccountMapper.updateNextId");

            session.commit();
            return result > 0;
        } catch (Exception e) {
            session.rollback();
            e.printStackTrace();
            return false;
        } finally {
            session.close();
        }
    }

    @Override
    public Account selectOne(Long id, String password) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("id", id);
            paramMap.put("password", password);
            return session.selectOne("com.geek.bams.mapper.AccountMapper.selectByIdAndPassword", paramMap);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            session.close();
        }
    }

    @Override
    public Account selectOne(Long id) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            return session.selectOne("com.geek.bams.mapper.AccountMapper.selectById", id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            session.close();
        }
    }

    @Override
    public List<Account> selectAll() {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            return session.selectList("com.geek.bams.mapper.AccountMapper.selectAll");
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<Account>(); // 返回空列表而不是null
        } finally {
            session.close();
        }
    }

    @Override
    public Long getId() {
        return id;
    }

    @Override
    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public boolean update(Account account) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            // 创建传递给MyBatis的参数Map
            Map<String, Object> paramMap = createParamMap(account);
            int result = session.update("com.geek.bams.mapper.AccountMapper.update", paramMap);
            session.commit();
            return result > 0;
        } catch (Exception e) {
            session.rollback();
            e.printStackTrace();
            return false;
        } finally {
            session.close();
        }
    }

    /**
     * 从数据库加载最大ID值
     */
    private void loadMaxIdFromDatabase() {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            // 从next_account_id表获取下一个ID
            Long nextId = session.selectOne("com.geek.bams.mapper.AccountMapper.getNextId");
            if (nextId != null) {
                this.id = nextId;
            } else {
                // 默认起始ID
                this.id = 862150212025110001L;
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 出错时使用默认ID
            this.id = 862150212025110001L;
        } finally {
            session.close();
        }
    }

    /**
     * 创建传递给MyBatis的参数Map
     */
    private Map<String, Object> createParamMap(Account account) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("id", account.getId());
        paramMap.put("name", account.getName());
        paramMap.put("password", account.getPassword());
        paramMap.put("personId", account.getPersonId());
        paramMap.put("email", account.getEmail());
        paramMap.put("balance", account.getBalance());

        // 根据账户类型设置特定字段
        if (account instanceof CreditAccount) {
            paramMap.put("accountType", account instanceof LoanCreditAccount ? "LOAN_CREDIT" : "CREDIT");
            // ceiling在Java中是double类型，在数据库中是BIGINT类型，需要转换
            paramMap.put("ceiling", Math.round(((CreditAccount) account).getCeiling()));
            if (account instanceof LoanCreditAccount) {
                paramMap.put("loanAmount", ((LoanCreditAccount) account).getLoanAmount());
            } else {
                paramMap.put("loanAmount", 0L);
            }
        } else if (account instanceof SavingAccount) {
            paramMap.put("accountType", account instanceof LoanSavingAccount ? "LOAN_SAVING" : "SAVING");
            paramMap.put("ceiling", 0L);
            if (account instanceof LoanSavingAccount) {
                paramMap.put("loanAmount", ((LoanSavingAccount) account).getLoanAmount());
            } else {
                paramMap.put("loanAmount", 0L);
            }
        }

        return paramMap;
    }

}

